package com.thread;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author: mayu
 * @date: 2021年04月12日 9:09
 */
public class TestABC123WithReentrantLock1 {
    public static void main(String[] args) {
        char[] chars1 = "ABCDEF".toCharArray();
        char[] chars2 = "123456".toCharArray();

        ReentrantLock lock = new ReentrantLock();
        Condition c1 = lock.newCondition();

        new Thread(() -> {
            /*Arrays.asList("A", "B", "C", "D", "E", "F").stream().forEach(item -> {
                lock.lock();
                try {
                    System.out.println(item);
                    c2.signal();
                    c1.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    lock.unlock();
                }
            });*/

            try {
                lock.lock();
                for (char c : chars1) {
                    System.out.print(c);
                    c1.signal();
                    c1.await();
                }
                //这里不加，程序不会停止
                c1.signal();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        }).start();

        new Thread(() -> {
            /*IntStream.range(1, 7).forEach(item -> {
                lock.lock();
                try {
                    System.out.println(item);
                    c1.signal();
                    c2.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    lock.unlock();
                }
            });*/

            try {
                lock.lock();
                for (char c : chars2) {
                    System.out.print(c);
                    c1.signal();
                    c1.await();
                }
                //这里不加，程序不会停止
                c1.signal();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        }).start();
    }
}
